﻿using System.Collections;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Altairis.FluffyCloud.Data;

namespace Altairis.FluffyCloud.WebCore.Controllers {

    public class RolesController : ApiController {

        public IEnumerable Get() {
            using (var dc = new FluffyDbContext()) {
                var q = from r in dc.Roles
                        select new {
                            RoleName = r.RoleName,
                            UserCount = r.Users.Count()
                        };
                return q.ToArray();
            }
        }

        public HttpResponseMessage Get(string id) {
            using (var dc = new FluffyDbContext()) {
                var role = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(id));
                if (role == null) {
                    return this.Request.CreateResponse(HttpStatusCode.NotFound);
                }
                else {
                    var r = new {
                        RoleName = role.RoleName,
                        UserCount = role.Users.Count(),
                        Members = role.Users.Select(x => x.UserName)
                    };
                    return this.Request.CreateResponse(HttpStatusCode.OK, r);
                }
            }
        }
    }
}